<template>
	<view>
		<cu-custom :isBack="true">
			<block slot="backText">
				{{groupName}}
			</block>
		</cu-custom>
		<view class="cu-list menu card-menu margin-top">
			<view class="cu-item" @tap="gotoDevice(item)" v-for="(item,index) in deviceBelongGroupList" :key="index">
				<view class="content">
					<text class="cuIcon-circlefill text-grey"></text>
					<text class="text-grey">{{item.name}}</text>
				</view>
				<button :style="{'--color': themeConfig.primaryColor}" v-if="item.haveChild" class="cu-btn shadow"
					@tap.stop="gotoGroup(item)">
					<view class="cuIcon-right"></view>
				</button>

			</view>
		</view>
	</view>
</template>
<script>
	import *
	as deviceBelongGroupApi from '@/api/iot/iotDeviceBelongGroupApi.js'
	export default {
		data() {
			return {
				deviceBelongGroupList: [],
				groupId: -1,
				groupName: '',
			}
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		onLoad(option) {
			if (option.groupId) {
				this.groupId = option.groupId
			}
			if (option.groupName) {
				this.groupName = option.groupName
			}
			this.init()
		},
		methods: {
			init() {
				this.getDeviceBelongGroupList()
			},
			getDeviceBelongGroupList() {
				deviceBelongGroupApi.getDeviceBelongGroupList({
					parentId: this.groupId
				}).then((res) => {
					if (res.data) {
						const deviceBelongGroupList = []
						res.data.forEach(group => {
							if (group.address && group.address !== '') {
								group.name = group.name + ' [' + group.address + ']'
							}
							deviceBelongGroupList.push({
								...group,
								haveChild: true
							})
						})
						this.deviceBelongGroupList = deviceBelongGroupList

						this.deviceBelongGroupList.forEach(group => {
							deviceBelongGroupApi.getDeviceBelongGroupList({
								parentId: group.groupId
							}).then((res2) => {
								if (!res2.data || res2.data.length === 0) {
									group.haveChild = false
								}
							})
						})

					}
				})
			},
			gotoDevice(item) {
				uni.navigateTo({
					url: `/pages/groupDevice/groupDevice?groupId=${item.groupId}&groupName=${item.name}`
				})
			},
			gotoGroup(item) {
				uni.navigateTo({
					url: `/pages/groupList/groupList?groupId=${item.groupId}&groupName=${item.name}`
				})
			},
		}
	}
</script>

<style>

</style>
